package com.zqh.orderquery.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zqh.myfmmall.clients.OrderItemQueryClient;
import com.zqh.myfmmall.constants.OrderStatus;
import com.zqh.myfmmall.entity.Orders;
import com.zqh.myfmmall.result.Result;
import com.zqh.myfmmall.entity.OrderItem;
import com.zqh.myfmmall.vo.OrdersVO;
import com.zqh.orderquery.dao.OrderDao;
import com.zqh.orderquery.service.OrderQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description :
 * @Author :kono淇杭哒、
 * @Create 2022-02-18 2:19
 */
@Service("orderQueryService")
public class OrderQueryServiceImpl extends ServiceImpl<OrderDao, Orders> implements OrderQueryService{
    @Autowired
    private OrderItemQueryClient orderItemQueryClient;

    @Override
    public Orders getOrderStatus(String orderId) {
        return query().eq("order_id",orderId).select("order_id","status").one();
    }

    @Override
    public List<OrdersVO> pageByStatus(String userId, Integer status, Integer pageSize, Integer pageNum) {
        List<OrdersVO> ordersVOS = new ArrayList<>();
        Page<Orders> ordersPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("user_id", userId).eq("status", status);
        page(ordersPage, ordersQueryWrapper);
        List<Orders> orders = ordersPage.getRecords();
        for (Orders order : orders) {
            Result result = orderItemQueryClient.listByOrderId(order.getOrderId());
            List<OrderItem> orderItems = JSON.parseArray(JSON.toJSONString(result.getData()),OrderItem.class);
            OrdersVO ordersVO = new OrdersVO(order, orderItems);
            ordersVOS.add(ordersVO);
        }
        return ordersVOS;
    }

    @Override
    public Map<String, Object> orderCounts(String userId) {
        HashMap<String, Object> countsMap = new HashMap<>();
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).groupBy("status").select("status,count(*) as count");
        List<Map<String, Object>> orderMaps = listMaps(queryWrapper);
        for (Map<String, Object> orderMap : orderMaps) {
            countsMap.put(((Integer) orderMap.get("status")).toString(),orderMap.get("count"));
        }
        return countsMap;
    }
}
